package com.wei.frame.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity;
import com.wei.frame.App;
import com.wei.frame.R;
import com.wei.frame.di.component.AppComponent;
import com.wei.frame.mvp.BasePresenter;
import com.wei.frame.mvp.IView;
import com.wei.frame.ui.widget.LoadingDialog;
import com.wei.frame.ui.widget.ToastUtils;
import com.wei.frame.utils.L;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.inject.Inject;

import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasAndroidInjector;
import dagger.internal.Beta;

/**
 * 作者:赵若位
 * 时间:2020/8/20 2:29
 * 功能:项目中所有Activity的基类
 */
@Beta
public abstract class BaseActivity<B extends ViewBinding, P extends BasePresenter> extends RxAppCompatActivity
        implements IView, HasAndroidInjector {

    protected final String TAG = this.getClass().getSimpleName();

    public abstract boolean isInject(AppComponent component);

    public abstract Class<B> getBindingClass();

    public abstract void initView();

    public abstract void initData();

    @Inject
    DispatchingAndroidInjector<Object> mAndroidInjector;

    AppComponent mComponent;

    /*ViewBinding*/
    protected B mBinding;
    /*Presenter层*/
    @Inject
    protected P mPresenter;
    /*根布局*/
    private View mRootView;
    /*加载进度条*/
    private LoadingDialog mLoadingDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mComponent = App.getComponent();
        if (isInject(mComponent)) {
            AndroidInjection.inject(this);
        }
        super.onCreate(savedInstanceState);
        mComponent.getAppManager().add(this);
        mBinding = createViewBinding();
        if (null != mBinding) {
            mRootView = mBinding.getRoot();
            setContentView(mRootView);
        }
        setStatusColor();
        initView();
        initData();
    }


    private B createViewBinding() {
        if (null != getBindingClass()) {
            try {
                Type type = getClass().getGenericSuperclass();
                Class<?> aClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
                Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
                return (B) method.invoke(null, getLayoutInflater());
            } catch (Exception e) {
                L.e(e.getMessage());
            }
        }
        return null;
    }

    /*设置状态的颜色和状态*/
    protected void setStatusColor() {
        ImmersionBar.with(this)
                .statusBarColor(android.R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();
    }

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
    }

    @Override
    @CallSuper
    protected void onResume() {
        super.onResume();
    }

    @Override
    @CallSuper
    protected void onPause() {
        super.onPause();
    }

    @Override
    @CallSuper
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getComponent().getAppManager().finishActivity(this);
    }


    @Override
    public View getRootView() {
        return null == mRootView ? (null == mBinding ?
                getWindow().getDecorView().findViewById(android.R.id.content) : mBinding.getRoot()) : mRootView;
    }

    @Override
    public BaseActivity getDependencies() {
        return this;
    }

    @Override
    public <T> LifecycleTransformer<T> bindRxLifecycle() {
        return bindUntilEvent(ActivityEvent.DESTROY);
    }

    @Override
    public void alert(@Nullable String msg) {
        if (!TextUtils.isEmpty(msg)) {
            runOnUiThread(() -> ToastUtils.getInstance().showToast(msg));
        }
    }

    @Override
    public void showLoading() {
        if (null == mLoadingDialog) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.showLoading();
    }

    @Override
    public void hideLoading() {
        if (null != mLoadingDialog) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void showDialog(@Nullable String message) {

    }

    @Override
    public void openActivity(@Nullable Class<? extends Activity> cls) {
        Intent it = new Intent(this, cls);
        startActivity(it);
    }

    private static long exitTime = 0;//点击后退记录时间

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (this instanceof MainActivity && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                alert(getString(R.string.finish_click_agin));
                exitTime = System.currentTimeMillis();
            } else {
                App.getComponent().getAppManager().exit();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public AndroidInjector<Object> androidInjector() {
        return mAndroidInjector;
    }
}
